using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GingerBeard.Utilities;
using GingerBeard.ColladaHelpers;
using System.IO;
using System.Diagnostics;
  
namespace ColladaToData
{
	class Program
	{
		static int Main(string[] args)
		{
			int exitCode = -1;
			CmdLineArgs cmdLineArgs = new CmdLineArgs();
			try
			{
				cmdLineArgs.SupportedArgs.Add(new CmdLineArgs.SupportedArg("IN", "Input collada file", CmdLineArgs.SupportedArg.RequirementType.Required));
				cmdLineArgs.SupportedArgs.Add(new CmdLineArgs.SupportedArg("OUT", "Output gk data file", CmdLineArgs.SupportedArg.RequirementType.Required));
				cmdLineArgs.SupportedArgs.Add(new CmdLineArgs.SupportedArg("PLATFORM", "Platform to generate data for", CmdLineArgs.SupportedArg.RequirementType.Required));

				cmdLineArgs.Initialise(args);

				if (!File.Exists(cmdLineArgs["IN"]))
					throw new Exception("Input file doesn't exist: " + cmdLineArgs["IN"]);

				System.Console.WriteLine(String.Format("[colladatodata] Converting '{0}' -> '{1}'", cmdLineArgs["IN"], cmdLineArgs["OUT"]));

				String tmpColladaFile = Path.GetTempFileName();
				Process p = new Process();
				p.StartInfo.FileName = @"Z:\ToolChain\Bin\ColladaAxisConversion.exe";
				p.StartInfo.Arguments = "\"" + cmdLineArgs["IN"] + "\" \"" + tmpColladaFile + "\"";
				p.StartInfo.CreateNoWindow = true;
				p.StartInfo.UseShellExecute = false;
				p.StartInfo.WorkingDirectory = @"Z:\ToolChain\Bin";
				p.Start();
				p.WaitForExit();

				if (p.ExitCode == 0)
				{
					COLLADA.Document doc = new COLLADA.Document(tmpColladaFile);

					Directory.CreateDirectory(Path.GetDirectoryName(cmdLineArgs["OUT"]));
					using (FileStream stream = new FileStream(cmdLineArgs["OUT"], FileMode.Create))
					{
						Exporter.Convert(doc, stream, cmdLineArgs["PLATFORM"]);
					}

					File.Delete(tmpColladaFile);
					exitCode = 0;
				}
				else
				{
					throw new Exception("Error conditioning input file");
				}
			}
			catch (CmdLineArgs.MissingRequiredArgException e)
			{
				cmdLineArgs.PrintUsage();
				System.Console.WriteLine(e.Message);
			}
			catch (Exception e)
			{
				System.Console.WriteLine(e.Message);
			}

			return exitCode;
		}
	}
}
